<?php
/**
 *
 * 只有在Server中才能使用协程。包括 http server，websocket server 和 server。
 */

$server = new Swoole\Http\Server('127.0.0.1', 9511);
//$server->set(array(
//    'daemonize' => 1,
//    'worker_num' => 8, //worker进程数量
//    'task_worker_num' => 8, //task进程数量 即为维持的MySQL连接的数量
//    'log_file' => '/var/www/swoole/cli/log/9511.log',
//));

/**
 *
 * 触发on request事件时，SWOOLE会开辟一个协程栈，对协程栈进行初始化
 */

$server->on('Request', function ($request, $response) {
    $sql = $request->post['sql'];
    $tcp_cli = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);

    if ($tcp_cli->connect('127.0.0.1', 9509, 10) === false) {

        $response->end("connect server failed.");
        return;
    }
//    $i = mt_rand(1,9999);
//    $sql = "select * from pay_order where id={$i}";
    $tcp_cli->send($sql."\r\n\r\n");//发送要执行的sql
    $ret = $tcp_cli->recv(100);
    $tcp_cli->close();
    if ($ret) {

        $response->end(" swoole response is ok");

    } else {
        $response->end(" recv failed error : {$tcp_cli->errCode}");
    }

});


$server->start();